<template>
    <view>
        <view class="sticky-top">
            <view class="nav-status-bar bg-blue pt-30"></view>
            <view class="header">
                <view class="item" v-for="item in model.tabs.data" @click="toggleTab(item.id)">
                    <view class="label" :class="{'active':item.id==model.tabs.active}">
                        {{item.label}}
                        <text class="text" v-if="model.order.totals[item.status+''+item.inprocess]">
                            {{model.order.totals[item.status+''+item.inprocess]}}
                        </text>
                    </view>
                    <view class="desc" :class="{'font-bold':item.id==model.tabs.active}">{{item.desc}}</view>
                    <view class="underline-white" v-if="item.id==model.tabs.active"></view>
                </view>
            </view>
            <view class="filter">
                <view class="tab">
                    <view class="flex-1" v-for="tab in model.search.dateTabs">
                        <view v-if="tab.id == 4" class="date">
                            <view :class="{'active':tab.id == model.search.activeTabId}">{{tab.name}}</view>
                            <uni-icons :type="model.search.dateRangeVisible ? 'top':'bottom'"
                                @click="hdDateRangeVisible" />
                        </view>
                        <view :class="{'active':tab.id == model.search.activeTabId}" @click="hdDateRange(tab.id)"
                            v-else>{{tab.name}}</view>
                    </view>
                </view>
                <view class="amount">
                    <view class="text">
                        配送费:￥{{model.order?.deliveryerIncome}}
                    </view>
                </view>
            </view>
        </view>
        <view class="range" v-if="model.search.dateRangeVisible">
            <uni-datetime-picker type="datetimerange" @change="chgDateRange" v-model="model.search.dateRange"
                ref="dateRangeRef" />
        </view>
        <view class="content">
            <view class="content__item" v-for="item in model.order.data" v-if="model.order.data?.length"
                @click="navDetail(item.id)">
                <view class="goods-header">
                    <view class="title">
                        <view class="table">#{{item.table_num}}</view>
                        <view class="store">{{item.store?.name || ''}}</view>
                    </view>
                    <view class="flex-1" v-if="model.tabs.active == 7">{{item.refunds?.length ? '已退款':'已取消'}}</view>
                    <view class="flex-1" v-else-if="model.tabs.active == 8">已完成</view>
                    <view class="flex-1" v-else>{{inStatusText(item.in_process_status)}}</view>
                </view>
                <view class="border-grey-b" v-if="item.consignee || item.consignee_phone || item.consignee_address">
                    <view class="flex-center">
                        <uni-icons type="person" size="46rpx" color="#909399"></uni-icons>
                        <view class="pad-10 base-color">{{item.consignee}}</view>
                    </view>
                    <view class="flex-center">
                        <uni-icons type="phone" size="46rpx" color="#94bcff"></uni-icons>
                        <view class="pad-10 text-link">{{item.consignee_phone}}</view>
                    </view>
                    <view class="flex-center">
                        <uni-icons type="home" size="46rpx" color="#909399"></uni-icons>
                        <view class="pad-10 secondary-color">{{item.consignee_address}}</view>
                    </view>
                </view>
                <view class="goods">
                    <view class="title">商品</view>
                    <view class="remark">
                        <view><text class="text-red">备注：</text><text class="base-color">{{item.remark}}</text></view>
                    </view>
                    <template v-for="row in item.goods">
                        <view class="quantity" v-if="row.is_weigh ? +row.weight : +row.quantity">
                            <view class="flex-3">
                                {{row.name}}
                                <template v-if="row.attributes?.length">
                                    ({{row.attributes.reduce((last,a)=>last.push(a.name) && last,[]).join(',')}})
                                </template>
                            </view>
                            <view class="flex-1">{{row.is_weigh?row.weight+'斤':'x'+row.quantity}}</view>
                            <view class="flex-1 text-right">
                                ￥{{((+row.price * 1000 * (row.is_weigh ? +row.weight : +row.quantity)) / 1000).toFixed(2)}}
                            </view>
                        </view>
                    </template>
                    <view class="change-amount" v-if="+item.change_amount||0">
                        <view class="flex-3">{{item.change_amount >= 0?'其他':'优惠'}}</view>
                        <view class="flex-1"></view>
                        <view class="flex-1 text-right">
                            {{item.change_amount >= 0?'￥'+item.change_amount:item.change_amount.toString().replace('-','-￥')}}
                        </view>
                    </view>
                    <view class="total">
                        <view class="flex-3">小计</view>
                        <view class="flex-1"></view>
                        <view class="flex-1 text-right">￥{{item.total}}</view>
                    </view>
                </view>
                <view class="footer">
                    <view class="desc">
                        <view class="flex-6">
                            <view>下单时间：{{item.created_at}}</view>
                            <view>订单号：{{item.order_num}}</view>
                            <view>取餐时间：{{item.pickup_time}}</view>
                        </view>
                    </view>
                    <view class="action" v-if="model.tabs.active == 4">
                        <view class="btn" @click.stop="hdCancel(item)">取消</view>
                        <view class="btn" @click.stop="hdComplete(item)">完成</view>
                    </view>
                </view>
            </view>
            <view class="empty" v-else-if="!model.init">
                <view class="bg-image"></view>
                <view class="text">{{Func.t("It's empty")}}</view>
            </view>
        </view>
    </view>
    <bgk-upgrade-dialog ref="upgradeRef" :desc="global.upgrade.desc" @upgrade="hdUpgrade"></bgk-upgrade-dialog>
</template>

<script lang="ts" setup>
    import { onPullDownRefresh, onLoad, onShow, onReachBottom } from '@dcloudio/uni-app'
    import { reactive, ref,nextTick } from 'vue'
    import { useGlobalStore } from '@/stores/global'
    import { downloadApp } from '@/utils/upgrade'
    import Func from '@/utils/functions'
    import Constants from '@/utils/constants'
    import { orderIndex, orderDeliveryer, orderUpdate } from './service'

    const global = useGlobalStore()
    const dateRangeRef = ref()
    const upgradeRef = ref()
    const model = reactive<any>({
        order: {
            data: [],
            id: 0,
            page: 1,
            total: 0,
            totals: [],
            deliveryerIncome: 0,
        },
        tabs: {
            active: 4,
            data: [
                { id: 4, label: '送', desc: '配送中', status: Constants.STATUS_IN_PROCESS, inprocess: Constants.IN_PROCESS_SHIPPED },
                { id: 7, label: '消', desc: '已取消', status: Constants.STATUS_CLOSED, inprocess: 0 },
                { id: 8, label: '完', desc: '已完成', status: Constants.STATUS_COMPLETED, inprocess: 0 }
            ]
        },
        search: {
            dateRange: [],
            dateRangeVisible: false,
            dateTabs: [
                { id: 1, name: '全部' },
                { id: 2, name: '今天' },
                { id: 3, name: '昨天' },
                { id: 4, name: '日期' }
            ],
            date: [],
            activeTabId: 1,
        },
        init: true,
    })

    const onrefresh = async () => {
        model.order.page = 1
        await loadOrders()
    }
    onPullDownRefresh(async () => {
        await onrefresh()
        uni.stopPullDownRefresh()
    })
    const toggleTab = id => {
        if (id != model.tabs.active) {
            model.tabs.active = id
            onrefresh()
        }
    }

    const inStatusText = status => {
        switch (status) {
            case Constants.IN_PROCESS_PENDING_PAYMENT:
                return '待支付'
            case Constants.IN_PROCESS_PENDING:
                return '支付确认中'
            case Constants.IN_PROCESS_PAYMENT_RECEIVED:
                return '已付款'
            case Constants.IN_PROCESS_IN_WAREHOUSE:
                return '备货中'
            case Constants.IN_PROCESS_PROCESSED:
                return '待发货'
            case Constants.IN_PROCESS_SHIPPED:
                return '配送中'
        }
        return '进行中'
    }

    const navDetail = id => {
        Func.navigateTo({
            url: '/pages/order/detail?id=' + id
        })
    }

    const loadOrders = async () => {
        try {
            Func.showLoading()
            let tab = model.tabs.data.find(r => r.id == model.tabs.active)
            const data = {
                status: tab.status,
                inprocess: tab.inprocess,
                date_start: model.search.date[0] || '',
                date_end: model.search.date[1] || '',
                page: model.order.page,
            }
            const res = await orderIndex(data)
            if (res?.code === Constants.API_SUCCESS) {
                if (model.order.page <= 1) {
                    model.order.data = res.data || []
                } else {
                    model.order.data = model.order.data.concat(res.data)
                }
                model.order.deliveryerIncome = Func.convertFenToYuan(res.deliveryer_income)
                model.order.totals = res?.total || []
                return model.order.total = res?.total[tab.status + '' + tab.inprocess] || 0
            }
            model.order.data = []
            model.order.total = 0
            throw res
        } catch (e) {
            console.log(e)
            e?.code == Constants.CLIENT_ERROR && (e.text = e.msg)
            Func.hdError(e, Func.t('Failed to load data'))
        } finally {
            Func.hideLoading()
        }
    }

    const getDate = n => {
        let today = new Date();
        let targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * n;
        today.setTime(targetday_milliseconds); //注意，这行是关键代码

        let tYear = today.getFullYear();
        let tMonth = today.getMonth();
        let tDate = today.getDate();
        const formatMonth = month => {
            var m = month;
            if (month.toString().length == 1) {
                m = "0" + month;
            }
            return m
        }
        tMonth = formatMonth(tMonth + 1);
        tDate = formatMonth(tDate);
        return tYear + "-" + tMonth + "-" + tDate;
    }
    const chgDateRange = date => {
        model.search.dateRangeVisible = false
        model.search.dateRange = date//清除日期v-model不起作用
        hdDateRange(date.length ? 4 : 1)
    }

    const hdDateRangeVisible = event => {
        model.search.dateRangeVisible = !model.search.dateRangeVisible
    }

    const hdDateRange = id => {
        model.search.activeTabId = id
        switch (id) {
            case 1:
                model.search.date = []
                break
            case 2:
                model.search.date = [getDate(0) + ' 00:00:00', getDate(0) + ' 23:59:59']
                break
            case 3:
                model.search.date = [getDate(-1) + ' 00:00:00', getDate(-1) + ' 23:59:59']
                break
            case 4:
                model.search.date = []
                if (model.search.dateRange.length == 2) {
                    model.search.date = [model.search.dateRange[0], model.search.dateRange[1]]
                }
                break
        }
        loadOrders()
    }

    const hdComplete = async data => {
        try {
            const rModal = await Func.showModal({
                content: '确定订单完成？'
            }, true)
            Func.showLoading()
            if (rModal?.confirm === true) {
                const res = await orderUpdate({
                    id: data.id,
                    delivery: 'completed',
                })
                if (res?.code === Constants.API_SUCCESS) {
                    Func.showToast({ title: '配送完成', mask: false })
                    return onrefresh()
                }
                throw res
            }
        } catch (e) {
            console.log(e)
            e?.code == Constants.CLIENT_ERROR && (e.text = e.msg)
            Func.hdError(e, '操作失败')
        } finally {
            Func.hideLoading()
        }
    }

    const hdCancel = async data => {
        try {
            const rModal = await Func.showModal({
                content: '确定取消订单？'
            }, true)
            Func.showLoading()
            if (rModal?.confirm === true) {
                const res = await orderUpdate({
                    id: data.id,
                    delivery: 'cancel',
                })
                if (res?.code === Constants.API_SUCCESS) {
                    Func.showToast({ title: '取消成功', mask: false })
                    return onrefresh()
                }
                throw res
            }
        } catch (e) {
            console.log(e)
            e?.code == Constants.CLIENT_ERROR && (e.text = e.msg)
            Func.hdError(e, '操作失败')
        } finally {
            Func.hideLoading()
        }
    }
    
    const hdUpgrade = () => {
        try {
            if (plus.os.name.toLowerCase() == 'ios') {
                plus.runtime.openURL('itms-apps://apps.apple.com/cn/app/id6504438044?mt=8', e => {
                    Func.showToast({ title: '应用无法更新' })
                })
            } else {
                downloadApp(global.upgrade.url, global.upgrade.type)
            }
        } catch (e) {
            console.log(e)
        } finally {
        }
    }

    const setOrderDeliveryer = async id => {
        try {
            Func.showLoading()
            const res = await orderDeliveryer({ value: id })
            if (res?.code === Constants.API_SUCCESS) {
                Func.showToast({ title: '配送成功', mask: false })
                await Func.sleep()
                return onrefresh()
            }
            throw res
        } catch (e) {
            console.log(e)
            if ([Constants.CLIENT_ERROR, Constants.PARAM_VALID_FAIL].includes(e?.code)) {
                e.text = e.msg
            }
            Func.hdError(e, '配送失败')
        } finally {
            Func.hideLoading()
        }
    }

    onReachBottom(() => {
        if (model.order.total > model.order.data.length) {
            model.order.page++
            loadOrders()
        }
    })
    
    onShow(() => {
        nextTick(() => {
            try {
                //判断App版本
                uni.$emit('checkVersionUpgradeEvent', () => {
                    if (Func.versionCompare(global.upgrade.ver, global.version) === 1) {
                        upgradeRef.value.open()
                    } else {
                        //加载公告
                        if (!global.notice.isRead) {
                            uni.$emit('checkNoticeEvent', () => {
                                if (global.notice.data?.length) {
                                    noticeRef.value.open()
                                }
                            })
                        }
                    }
                })
            } catch (e) {
                console.log(e)
            } finally {
            }
        })
    })

    onLoad(async () => {
        uni.onTabBarMidButtonTap(async () => {
            const res = await uni.scanCode({ scanType: ['qrCode'], autoZoom: false })
            if (res?.result) {
                return await setOrderDeliveryer(res.result)
            }
            Func.showToast({ title: '获取订单失败' })
        });
        model.search.dateRange = [getDate(0) + ' 00:00:00', getDate(0) + ' 23:59:59']
        await loadOrders()
        model.init = false
    })
</script>

<style lang="scss" scoped>
    $bar-height: var(--status-bar-height);

    .font-bold {
        font-weight: bold;
    }

    .flex-1 {
        flex: 1;
    }

    .flex-3 {
        flex: 3;
    }

    .flex-6 {
        flex: 6;
    }

    .underline-white {
        height: 2rpx;
        margin: 0 10rpx;
        background: #fff;
    }

    .text-link {
        color: #94bcff;
    }

    .text-red {
        color: #e43d33;
    }

    .text-right {
        text-align: right;
    }

    .border-grey-b {
        border-bottom: 1px solid #f0f0f0;
    }

    .bg-grey {
        background: #fff;
        color: #6a6a6a;
    }

    .bg-blue {
        background-color: #33aafc;
    }

    .flex-center {
        display: flex;
        align-items: center;
    }

    .base-color {
        color: #6a6a6a;
    }

    .secondary-color {
        color: #909399;
    }

    .pad-10 {
        padding: 10rpx;
    }
    .pt-30 {
        padding: 30rpx;
    }

    .sticky-top {
        position: sticky;
        top: 0;
    }

    .header {
        display: flex;
        justify-content: space-around;
        background: #33aafc;
        color: #fff;
        padding: 5rpx 10rpx;

        & .item {
            text-align: center;

            & .label {
                position: relative;
                font-size: 38rpx;
                background: rgba(28, 134, 238, 0.5);
                padding: 10rpx;
                font-weight: 600;
                border-radius: 10rpx;

                & .text {
                    position: absolute;
                    color: #fff;
                    background: #e43d33;
                    border-radius: 50rpx;
                    padding: 4rpx 10rpx;
                    top: -5rpx;
                    right: -10rpx;
                    font-size: 22rpx;
                }
            }

            & .desc {
                font-size: 26rpx;
                padding: 8rpx 0;
            }

            & .active {
                background-color: #fff;
                color: #33aafc;
            }
        }
    }

    .filter {
        background-color: #fff;
        border: 1px solid #c7c7c7;
        color: #6a6a6a;

        & .tab {
            display: flex;
            align-items: center;
            text-align: center;
            padding: 16rpx 0;

            & .active {
                color: #33aafc;
            }

            & .date {
                display: flex;
                align-items: center;
                justify-content: center;
                position: relative;
            }
        }

        & .amount {
            padding: 0 20rpx;
            font-size: 28rpx;

            & .text {
                padding: 10rpx 0;
                border-top: 1px solid #ededed;
            }
        }
    }

    .range {
        position: absolute;
        top: 25vh;
        right: 10rpx;
        width: 97vw;
        background-color: #fff;
    }

    .content {
        background-color: #f7f7f7;

        &__item {
            padding: 20rpx;
            background-color: #fff;
            margin-bottom: 20rpx;

            & .goods-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                border-bottom: 1px solid #f0f0f0;
                padding-bottom: 10rpx;

                & .title {
                    display: flex;
                    align-items: center;
                    flex: 6;
                    padding-right: 10rpx;

                    & .store {
                        margin-left: 20rpx;
                    }
                }

                & .table {
                    background-color: #33aafc;
                    color: #fff;
                    padding: 10rpx;
                    border-radius: 10rpx;
                }
            }

            & .goods {
                @extend .border-grey-b;

                & .title {
                    font-weight: bold;
                    color: #3a3a3a;
                    padding: 6rpx;
                }

                & .remark {
                    display: flex;
                    align-items: center;
                    color: #6a6a6a;
                    padding: 6rpx;
                }

                & .quantity {
                    display: flex;
                    align-items: center;
                    color: #3a3a3a;
                    padding: 6rpx;
                }

                & .change-amount {
                    display: flex;
                    align-items: center;
                    color: #6a6a6a;
                    padding: 6rpx;
                }

                & .total {
                    display: flex;
                    align-items: center;
                    color: #6a6a6a;
                    padding: 6rpx;
                }
            }

            & .refund {
                border-bottom: 1px solid #f0f0f0;
                padding: 10rpx 0;

                & .text {
                    font-weight: bold;
                    color: #e43d33;
                    padding: 10rpx 0;
                }

                & .desc {
                    color: #3a3a3a;

                    & .status {
                        font-weight: bold;
                    }

                    & .img {
                        display: inline-block;
                        width: 160rpx;
                        height: 160rpx;
                        margin-right: 10rpx;
                    }
                }
            }

            & .footer {
                border-bottom: 1px solid #f0f0f0;
                padding: 10rpx 0;

                & .desc {
                    display: flex;
                    color: #909399;
                }

                & .action {
                    display: flex;
                    align-items: center;
                    justify-content: flex-end;
                    color: #6a6a6a;
                    text-align: right;
                    padding-top: 20rpx;

                    & .btn {
                        border: 1px solid #ededed;
                        padding: 10rpx 20rpx;
                        background: #33aafc;
                        color: #fff;
                        border-radius: 10rpx;
                        margin-left: 20rpx;
                    }
                }
            }
        }
    }

    .empty {
        height: 80vh;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        & .bg-image {
            background: center / contain no-repeat url('../../static/images/empty.png');
            width: 90vw;
            height: 40vh;
        }

        & .text {
            color: #6a6a6a;
        }
    }
</style>